package cn.xerllent.wxtp.handler;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import cn.xerllent.wxtp.entity.WxAdmin;
import cn.xerllent.wxtp.service.WxAdminService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.WxCpTpAdmin;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * 应用管理员变化通知回调
 *
 */
@Component
@Slf4j
public class AppAdminChangetHandler extends AbstractHandler {

	@Autowired
	private WxAdminService wxAdminService;

	@Override
	public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage, Map<String, Object> context,
			WxCpTpService wxCpTpService, WxSessionManager sessionManager) {
		String suiteId = wxCpTpService.getWxCpTpConfigStorage().getSuiteId();
		String corpId = wxMessage.getToUserName(); // 授权企业id
		Integer agentId = Integer.parseInt(wxMessage.getAgentID());

		//获取应用管理员并设置
		try {
			WxCpTpAdmin wxCpTpAdmin = wxCpTpService.getAdminList(corpId, agentId);
			List<WxAdmin> list = wxCpTpAdmin.getAdmin().stream().map(a ->{
				return new WxAdmin().setCorpId(corpId).setSuiteId(suiteId).setAgentId(agentId).setUserId(a.getUserId()).setAuthType(a.getAuthType());
			}).collect(Collectors.toList());
			wxAdminService.remove(new LambdaUpdateWrapper<WxAdmin>().eq(WxAdmin::getCorpId, corpId).eq(WxAdmin::getAgentId, agentId));
			wxAdminService.saveBatch(list);

			log.info("应用管理员变化通知回调处理完毕.");
		} catch (WxErrorException e) {
			log.error("应用管理员变化通知回调处理 err:" , e);
		}

		return null;
	}

}
